package com.ctc.test.fragment;

import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

import com.ctc.test.serial.SerialPortFinder;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.IdRes;
import androidx.fragment.app.Fragment;

public class BaseFragment extends Fragment
{
    /** 打印TAG */
    protected String TAG = getClass().getSimpleName();
    /** 绑定的界面 */
    protected View bindView;
    /** 显示的消息列表内容 */
    private List<String> listString = new ArrayList<>();

    /** 显示的消息列表适配器 */
    protected ArrayAdapter<String> adapterMsg;
    /** 串口选择器适配器 */
    protected ArrayAdapter<String> adapterSerialPort;

    /** 显示的消息列表控件 */
    protected ListView listViewMsg;
    /** 串口选择器控件 */
    protected Spinner spinnerSerial;

    /**
     * 初始化显示的消息列表
     *
     * @param id 列表控件ID
     */
    protected void initMsgList(@IdRes int id)
    {
        if (listViewMsg == null && bindView != null)
        {
            listViewMsg = bindView.findViewById(id);
            adapterMsg = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listString);
            listViewMsg.setAdapter(adapterMsg);
        }
    }

    /**
     * 初始化串口选择器
     *
     * @param id 选择器控件ID
     */
    protected void initSerialSpinner(@IdRes int id)
    {
        ArrayList<String> serialPortList = SerialPortFinder.getSerialPortPath();
        if (spinnerSerial == null && bindView != null)
        {
            spinnerSerial = bindView.findViewById(id);
            adapterSerialPort = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, serialPortList);
            adapterSerialPort.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerSerial.setAdapter(adapterSerialPort);
        }
    }

    /**
     * 添加显示的消息
     *
     * @param str 消息内容
     */
    public synchronized void addMsg(String str)
    {
        Log.i(TAG, str);
        if (listViewMsg != null)
        {
            listViewMsg.post(() -> {
                listString.add(0, str);
                while (listString.size() > 100)
                {
                    listString.remove(listString.size() - 1);
                }
                adapterMsg.notifyDataSetChanged();
            });
        }
    }
}
